<template>
  <div>
    <div class="search">
      <el-form>
        <el-form-item label="人员搜索:" label-width="82px">
          <el-input v-model="search" placeholder="请输入" />
          <el-button type="primary" icon="el-icon-search" @click="getSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="push"
      >
        新增
      </el-button>
      <el-table style="width: 100%" :data="tableData">
        <el-table-column label="序号" type="index"> </el-table-column>
        <el-table-column label="人员名称" prop="userName"> </el-table-column>
        <el-table-column label="归属区域" prop="regionName"> </el-table-column>
        <el-table-column label="角色" prop="role.roleName"> </el-table-column>
        <el-table-column label="联系电话" prop="mobile"> </el-table-column>
        <el-table-column label="操作" prop="id">
          <template #default="{ row: { id } }">
            <el-button @click="update(id)">修改</el-button>
            <el-button @click="deleted(id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="slot,prev,next"
          background
          :page-size="10"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
          @current-change="changeCurrent"
        >
          <slot>
            <span class="el-pagination__total">
              共{{ total }}条记录&nbsp;&nbsp;第&nbsp;{{ query.pageIndex }}/{{
                totalPage
              }}&nbsp;页
            </span>
          </slot>
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="40%">
      <el-form
        :model="peopleInfo"
        :rules="rules"
        ref="form"
        label-width="140px"
      >
        <el-form-item label="人员名称：" prop="userName">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="peopleInfo.userName"
          >
            <span slot="suffix">{{ peopleInfo.userName.length }}/5</span>
          </el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-select v-model="peopleInfo.roleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="peopleInfo.mobile"
          >
            <span slot="suffix">{{ peopleInfo.mobile.length }}/11</span>
          </el-input>
        </el-form-item>
        <el-form-item label="负责区域：" prop="regionId">
          <el-select v-model="peopleInfo.regionId" placeholder="请选择">
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像：" prop="image">
          <el-upload
            action="http://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
            class="avatar-uploader"
            name="fileName"
            :show-file-list="false"
            :before-upload="validateFile"
            :on-success="getImgUrl"
          >
            <img
              v-if="peopleInfo.image"
              :src="peopleInfo.image"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip">支持扩展名：jpg、png，文件不得大于100kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态：">
          <el-checkbox v-model="peopleInfo.status">是否启用</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="setback">取 消</el-button>
        <el-button type="primary" @click="confirmInfo"> 确 定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  propleList,
  areaList,
  roleList,
  searchList,
  pushPeople,
  peopleInfo,
  updateThis,
  deleted
} from '@/api/people-admin'
export default {
  name: 'people-admin',
  components: {},
  props: {},
  data() {
    return {
      // 搜索
      search: '',
      // 列表数据
      tableData: [],
      // 查询参数
      query: {
        pageIndex: 1,
        pageSize: 10,
        userName: ''
      },
      // 人员总数
      total: 0,
      // 信息框显示
      dialogVisible: false,
      // 角色列表
      roleList: [],
      // 区域列表
      areaList: [],
      // 人员信息
      peopleInfo: {
        image: '',
        mobile: '',
        regionId: '',
        regionName: '',
        roleId: null,
        status: false,
        userName: ''
      },
      // 校验
      rules: {
        userName: [
          { required: true, message: '请输入', triggle: 'blur' },
          { min: 1, max: 5, message: '请输入', triggle: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择', triggle: 'blur', type: 'number' }
        ],
        mobile: [
          {
            required: true,
            message: '请输入',
            triggle: 'blur'
          },
          {
            Pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            min: 11,
            max: 11,
            message: '请输入正确的手机号',
            triggle: 'blur'
          }
        ],
        regionId: [{ required: true, message: '请选择区域', triggle: 'blur' }],
        image: [{ required: true, message: '请上传图片', triggle: 'blur' }]
      },
      title: '',
      userId: null
    }
  },
  computed: {
    totalPage() {
      const num = this.total / 10
      return Math.floor(num) + 1
    }
  },
  watch: {},
  methods: {
    // 获取人员列表
    async getList() {
      const res = await propleList(this.query)
      this.tableData = res.currentPageRecords
      this.total = res.totalCount - 0
    },
    // 获取区域数据
    async getAreaList() {
      const res = await areaList()
      this.areaList = res.currentPageRecords
    },
    // 获取角色数据
    async getRoleList() {
      const res = await roleList()
      this.roleList = res
    },
    // 当前页数据
    changeCurrent(index) {
      this.query.pageIndex = index
      this.getList()
    },
    // 检索数据
    async getSearch() {
      this.query.userName = this.search
      const res = await searchList(this.query)
      this.tableData = res.currentPageRecords
      this.total = res.totalCount - 0
    },
    // 添加成员信息框
    push() {
      this.title = '新增人员'
      this.dialogVisible = true
      this.getAreaList()
      this.getRoleList()
    },
    // 图片上传成功
    getImgUrl(res) {
      this.peopleInfo.image = res
    },
    // 上传前
    validateFile(file) {
      const type = ['image/jpeg', 'image/png']
      const isLt100kb = file.size < 102400
      const isType = type.includes(file.type)
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt100kb) {
        this.$message.error('上传头像图片大小不能超过 100KB!')
      }
      return isType && isLt100kb
    },
    // 确认添加/修改成员
    async confirmInfo() {
      try {
        if (this.title === '新增人员') {
          this.$refs.form.validate()
          const obj = {}
          for (const key in this.peopleInfo) {
            obj[key] = this.peopleInfo[key]
          }
          const index = this.areaList.findIndex((_) => _.id === obj.regionId)
          obj.regionName = this.areaList[index].name
          await pushPeople(obj)
          this.$message.success('添加人员成功')
        } else {
          // 有复用
          this.$refs.form.validate()
          const obj = {}
          for (const key in this.peopleInfo) {
            obj[key] = this.peopleInfo[key]
          }
          const index = this.areaList.findIndex((_) => _.id === obj.regionId)
          obj.regionName = this.areaList[index].name
          // ------
          await updateThis(this.userId, obj)
          this.$message.success('修改人员成功')
        }
        this.getList()
        this.$refs.form.resetFields()
        this.dialogVisible = false
      } catch (error) {
        console.log(error)
      }
    },
    // 取消操作
    setback() {
      this.peopleInfo = {
        image: '',
        mobile: '',
        regionId: '',
        regionName: '',
        roleId: null,
        status: false,
        userName: ''
      }
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    // 修改成员
    async update(id) {
      const res = await peopleInfo(id)
      for (const key in this.peopleInfo) {
        this.peopleInfo[key] = res[key]
      }
      this.push()
      this.title = '编辑人员'
      this.userId = id
    },
    // 删除成员
    async deleted(id) {
      try {
        await deleted(id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style scoped lang="scss">
.el-input {
  width: 200px;
}
.el-button {
  margin-left: 10px;
}
.pagination {
  padding: 32px 16px;

  .el-pagination {
    display: flex;
    ::v-deep .el-pagination__total {
      flex: 1;
    }
    ::v-deep .btn-prev {
      width: 70px;
      height: 32px;
      background: #d5ddf8;
      &:disabled {
        background: #edf0f9;
      }
    }

    ::v-deep .btn-next {
      width: 70px;
      height: 32px;
      background: #d5ddf8;
    }
  }
}
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  line-height: 84px;
  text-align: center;
}
.avatar {
  width: 84px;
  height: 84px;
  display: block;
}
</style>
